import pandas as pd

from tools.Conver_Tools import Conver_Tools
from tools.Time_Tools import Time_Tools


class HouseVisitRecordsServer:
    def __init__(self, house_records_path, resident_sample_path):
        # 加载住户样本数据
        house_df = pd.read_csv(resident_sample_path, encoding='GBK')

        self.file_path = house_records_path
        # 加载访户数据
        house_records_df = pd.read_csv(self.file_path, encoding='GBK')
        self.house_records_df = house_records_df
        # 获取导出年份月份
        self.year_mouth = Time_Tools.get_file_year_mouth(self.file_path, "5105.")
        self.mouth = Time_Tools.get_file_mouth(self.file_path, "5105.")

        # 组装住户样本数据
        ## 获取住户所在点位
        house_df['Point'] = house_df['户编码'].apply(lambda scode: str(scode)[0:str(scode).find(".")]).astype(int)
        house_df['县码'] = house_df['住户ID'].str[0:6]
        # 排除新开户的情况
        house_df = house_df[house_df["开户时间"] < self.year_mouth]
        records_df = pd.DataFrame(house_records_df.groupby('被访户编码').size().reset_index(name="count"))
        # 将访户数据挂载
        self.records_df = pd.merge(house_df, records_df, left_on='住户ID', right_on="被访户编码", how='left')
        # 将空值填为0
        self.records_df.fillna({"count": 0}, inplace=True)

        # 过滤不符合条件的区县和点位 访户次数 < 2 次  户数 < 10 户
        showAllData = self.records_df[self.records_df['count'] < 2][['县码', 'Point', '户编码', 'count']]

        self.errorData = Conver_Tools.list_to_dict(list(pd.DataFrame(showAllData.groupby(['县码', 'Point']))[0]))



    def get_area_data(self, area_code) -> dict:
        """
        通过区域ID，获取访户数据
        :param area_code: 区域ID
        :return: 返回包含访户数据字典，point,data key  value 一维数组
        """
        # 筛选对应县区
        dataDf = self.records_df[self.records_df['县码'] == str(area_code)].copy()
        # 汇总访户次数
        dataDf = pd.DataFrame(dataDf.groupby('Point')['count'].sum().reset_index())
        return {
            "point": list(dataDf['Point']),
            "data": list(dataDf['count'])
        }

    def get_area_and_points(self, area_code, point) -> dict:
        """
        通过区域ID和点位point获取访户数据
        :param area_code: 区域ID
        :param point: 点位
        :return: 返回包含访户数据字典，point,data key  value 一维数组
        """

        # 筛选对应县区和点位几访户次数
        dataDf = self.records_df[(self.records_df['县码'] == str(area_code)) & (self.records_df['Point'] == point)]

        return {
            "houseID": list(dataDf['户编码']),
            "data": list(dataDf['count'])
        }

    def get_visit_time_null(self):
        """
        访户时间为空
        :return:
        """
        temp = self.house_records_df.copy()
        temp = temp[temp["访户时间"].isna()]
        return temp.drop_duplicates(subset=["被访户编码"]).sort_values(by=["被访户编码","县码","SCODE"]).reset_index(drop=True).fillna(value="")

    def get_visit_time_no_current_month(self):
        """
        访户时间非当月
        :return:
        """
        temp = self.house_records_df.copy()
        temp = temp[~temp["访户时间"].isna()]
        temp["访户时间"] = pd.to_datetime(temp["访户时间"])
        temp["访户月份"] = temp["访户时间"].dt.month
        temp = temp[temp["访户月份"] != self.mouth]
        return temp.drop_duplicates(subset=["被访户编码"]).sort_values(by=["被访户编码","县码","SCODE"]).reset_index(drop=True).fillna(value="")

    def get_visitor_phone_null(self):
        """
        访问人电话为空
        :return:
        """
        temp = self.house_records_df.copy()
        temp = temp[temp["访问人电话"].isna()]
        return temp.drop_duplicates(subset=["被访户编码"]).sort_values(by=["被访户编码","县码","SCODE"]).reset_index(drop=True).fillna(value="")

    def get_error_visit(self):
        """
        无效访问：访户内容为空 且 特殊说明为空  且 无上传图片
        :return:
        """
        temp = self.house_records_df.copy()
        temp = temp[temp["访户内容"].isna()]
        temp = temp[temp["特殊说明"].isna()]
        temp = temp[temp["有无上传图片"] == "无"]
        return temp.drop_duplicates(subset=["被访户编码"]).sort_values(by=["被访户编码","县码","SCODE"]).reset_index(drop=True).fillna(value="")